<template>
  <div class="pay_detail">
    <div class="amount">
      <span>￥</span>
      <span style="font-size: 30px;">{{ Number(data.realitycostMoney).toFixed(2) }}</span>
      <div class="amount_zw">{{ number2text(Number(data.realitycostMoney)) }}</div>
    </div>
    <div class="info">
      <div class="com_info name">
        <div>党员姓名</div>
        <div>{{ data.pmName }}</div>
      </div>
      <div class="com_info batch">
        <div>缴纳批次</div>
        <div>{{ data.particularYear }}第{{ data.payQuarter }}季度</div>
      </div>
      <div class="com_info recive_account">
        <div>收款账户</div>
        <div>东吴证券有限公司</div>
      </div>
    </div>
    <div class="operate">
      <div class="btn" @click="startPay">
        立即支付
      </div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { IWxConfigData, useCommonStore } from '@/store/common';
import { showConfirmDialog } from 'vant';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { IUnPay } from '../pay/type';
import { getJsSDKConfigApi } from '@/api/wechat';
import { useWxSDK } from '@/hooks/useWxSDK';
import { fetchPay } from '@/api/pay';
const store = useCommonStore()
const route = useRoute()
const data: IUnPay = route.query as any
const router = useRouter()
function number2text(number: number, type = 'upper') {
  // 配置
  const confs = {
    lower: {
      num: ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'],
      unit: ['', '十', '百', '千', '万'],
      level: ['', '万', '亿']
    },
    upper: {
      num: ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'],
      unit: ['', '拾', '佰', '仟'],
      level: ['', '万', '亿']
    },
    decimal: {
      unit: ['分', '角']
    },
    maxNumber: 999999999999.99
  }
  // 过滤不合法参数
  if (Number(number) > confs.maxNumber) {
    console.error(`The maxNumber is ${confs.maxNumber}. ${number} is bigger than it!`)
    return false
  }
  const conf = confs[type]
  const numbers = String(Number(number).toFixed(2)).split('.')
  const integer = numbers[0].split('')
  const decimal = Number(numbers[1]) === 0 ? [] : numbers[1].split('')
  // 四位分级
  const levels = integer.reverse().reduce((pre, item, idx) => {
    let level = pre[0] && pre[0].length < 4 ? pre[0] : []
    let value = item === '0' ? conf.num[item] : conf.num[item] + conf.unit[idx % 4]
    level.unshift(value)
    if (level.length === 1) {
      pre.unshift(level)
    } else {
      pre[0] = level
    }
    return pre
  }, [])
  // 整数部分
  const _integer = levels.reduce((pre, item, idx) => {
    let _level = conf.level[levels.length - idx - 1]
    let _item = item.join('').replace(/(零)\1+/g, '$1') // 连续多个零字的部分设置为单个零字
    // 如果这一级只有一个零字，则去掉这级
    if (_item === '零') {
      _item = ''
      _level = ''
      // 否则如果末尾为零字，则去掉这个零字
    } else if (_item[_item.length - 1] === '零') {
      _item = _item.slice(0, _item.length - 1)
    }
    return pre + _item + _level
  }, '')
  // 小数部分
  let _decimal = decimal
    .map((item, idx) => {
      const unit = confs.decimal.unit
      const _unit = item !== '0' ? unit[unit.length - idx - 1] : ''
      return `${conf.num[item]}${_unit}`
    })
    .join('')
  // 如果是整数，则补个整字
  return `${_integer}元` + (_decimal || '整')
}
async function initWxSdk() {
  let token = localStorage.getItem('token') || ''
  const store = useCommonStore();
  const { initConfig } = useWxSDK()
  let wxRes: Boolean = false
  if (!store.hasWxConfigData) {
    try {
      let res = await getJsSDKConfigApi({
        token
      })
      let data: IWxConfigData = res.data
      store.saveWxConfigData(data)
      store.saveHasWxConfig(true)
      wxRes = await initConfig({
        appid: data.appid,
        signature: data.signature,
        timestamp: data.timestamp,
        noncestr: data.noncestr,
        jsApiList: ['chooseWXPay'],
      })
    } catch (error) {
      console.log(error);
    }
  } else {
    const data: IWxConfigData = store.wxConfigData
    wxRes = await initConfig({
      appid: data.appid,
      signature: data.signature,
      timestamp: data.timestamp,
      noncestr: data.noncestr,
      jsApiList: ['chooseWXPay'],
    })
  }
  if (wxRes) {
    console.log('wxRes,wx初始化完成');
  }
}
const startPay = async function () {
  let res = await showConfirmDialog({
    message:
      '确认支付？',
  })
  if (!res) return
  if (store.hasWxConfigData) {
    let prePayRes: any = await fetchPay({
      id: data.id,
      payAmount: data.realitycostMoney,
      description: `${data.particularYear}第${data.payQuarter}季度党费`
    })
    if (prePayRes.code == 200) {
      const payInfo = prePayRes.payInfo
      wx.invoke('getBrandWCPayRequest', {
        "appId": payInfo.appId,     //公众号ID，由商户传入     
        "timeStamp": payInfo.timestamp,     //时间戳，自1970年以来的秒数     
        "nonceStr": payInfo.noncestr,      //随机串     
        "package": payInfo.packageval,
        "signType": payInfo.signtype,     //微信签名方式：     
        "paySign": payInfo.paysign //微信签名 
      }, function (res: any) {
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          router.push('pay-res/?status=success')
        } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
        } else if (res.err_msg = 'get_brand_wcpay_request:fail') {
          router.push('pay-res/?status=fail')
        }
      });
    } else {
      alert('预支付失败');
    }

  }
}
initWxSdk();


</script>
<style lang='less' scoped>
.pay_detail {
  padding: 15px 20px;
  box-sizing: border-box;
  border-radius: 6px;
  color: black;
  background-color: #f6f8fa;
  height: 100%;

  .com_info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;

    div:nth-child(1) {
      font-size: 14px;
      color: #9ba4b5;
    }

    div:nth-child(2) {
      font-size: 16px;
      color: black;
    }

    &:last-child {
      margin-bottom: 0;
    }
  }

  .info {
    padding: 25px 15px;
    background-color: #fff;
    border-radius: 6px;
  }

  .operate {
    margin-top: 15px;
  }

  .amount_zw {
    font-size: 14px;
    color: #8994a8;
  }

  .amount {
    font-weight: 900;
    text-align: center;
    margin-bottom: 30px;
  }

  .name {
    font-size: 16px;
  }

  .date {
    color: #8893a7;
    font-size: 14px;
    margin-top: 7px;

  }

  .btn {
    padding: 10px 15px;
    border-radius: 35px;
    background-color: #d10201;
    color: white;
    font-size: 14px;
  }
}
</style>